package com.innovation.chengzhangriji.ui.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.innovation.chengzhangriji.ChZhRJApplication;

// Android Bug
// android:gravity="right" 和 android:singleLine="true" 同时设置时
// EditText 第二次呼出输入法的时候，整个window不能adjustPan.
// 详情参考 http://blog.csdn.net/zhangjizxc/article/details/23786071
public class CuteMiniEditText extends EditText implements TextWatcher, View.OnKeyListener {

    private static final int MAX_LENGTH = 10;

    private interface CloseListener {
        void close();
    }

    private CloseListener listener;

    public CuteMiniEditText(Context context) {
        super(context);
        init(context);
    }

    public CuteMiniEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CuteMiniEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > MAX_LENGTH) {
            setText(s.subSequence(0, MAX_LENGTH));
            setSelection(MAX_LENGTH);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER) {
            if (listener != null) {
                listener.close();
            }
            return true;
        }
        return false;
    }

    private void init(final Context context) {
        setTypeface(((ChZhRJApplication) context.getApplicationContext()).getTypeface());
        addTextChangedListener(this);
        setOnKeyListener(this);
        listener = new CloseListener() {
            @Override
            public void close() {
                closeInput(context);
            }
        };
    }

    private void closeInput(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

}
